<template>
  <div class="app-container">

    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <el-input v-model="listQuery.community" clearable class="filter-item" style="width: 200px;" placeholder="小区名称"/>
      <el-input v-model="listQuery.fullName" clearable class="filter-item" style="width: 200px;" placeholder="房屋全称"/>
      <el-input v-model="listQuery.landlord" clearable class="filter-item" style="width: 200px;" placeholder="房东姓名"/>
      <el-date-picker
        class="filter-item"
        value-format="yyyy-MM-dd"
        v-model="listQuery.playTime"
        type="date"
        placeholder="请选择交租时间">
      </el-date-picker>
      <el-select v-model="listQuery.playFlag" clearable class="filter-item" filterable placeholder="交租状态">
        <el-option
          v-for="item in playStatusOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value"/>
      </el-select>
      <el-select v-model="listQuery.leaseStatus" clearable class="filter-item" filterable placeholder="租约状态">
        <el-option
          v-for="item in leaseStatusOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value"/>
      </el-select>

      <el-button v-permission="['GET /admin/house/list']" class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">查找</el-button>
      <el-button v-permission="['POST /admin/house/add']" class="filter-item" type="primary" icon="el-icon-edit" @click="handleCreate">添加</el-button>
      <el-button v-permission="['GET /admin/house/playFlagUpdate']" class="filter-item" type="primary" icon="el-icon-edit" @click="updataRenovate">立即刷新</el-button>
      <!--<el-button :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">导出</el-button>-->
    </div>

    <!-- 查询结果 -->
    <el-table v-loading="listLoading" :data="list" element-loading-text="正在查询中。。。" border fit highlight-current-row style="width: 100%" row-style="height:35px" cell-style="padding:0">
      <el-table-column type="expand">
        <template slot-scope="props">
          <el-form label-position="left" inline class="demo-table-expand">
            <el-form-item label="房东姓名">
              <span>{{ props.row.landlord }}</span>
            </el-form-item>
            <!--            <el-form-item label="房东姓名" prop="sex">
              <el-select v-model="scope.row.sex" >
                <el-option label="0" value='男'></el-option>
                <el-option label="1" value='女'></el-option>
              </el-select>
            </el-form-item>-->
            <!--            <el-form-item label="房东性别">

                <el-tag v-if="{{scope.row.sex}} === '0'" size="small" type="success">男</el-tag>
                <el-tag v-if="{{scope.row.sex}} === '1'" size="small" type="warning">女</el-tag>

             &lt;!&ndash; <span>{{ props.row.landlord }}</span>&ndash;&gt;
            </el-form-item>-->
            <el-form-item label="联系方式">
              <span>{{ props.row.phone }}</span>
            </el-form-item>
            <el-form-item label="付租账号">
              <span>{{ props.row.accountNumber }}</span>
            </el-form-item>
            <el-form-item label="电户号">
              <span>{{ props.row.electricNumber }}</span>
            </el-form-item>
            <el-form-item label="水户号">
              <span>{{ props.row.waterNumber }}</span>
            </el-form-item>
            <el-form-item label="燃气户号">
              <span>{{ props.row.gasNumber }}</span>
            </el-form-item>
            <el-form-item label="楼栋号">
              <span>{{ props.row.building }}</span>
            </el-form-item>
            <el-form-item label="房间号">
              <span>{{ props.row.houseNumber }}</span>
            </el-form-item>
            <el-form-item label="租金价格">
              <span>{{ props.row.rent }}</span>
            </el-form-item>
            <el-form-item label="起租时间">
              <span>{{ props.row.beginDate }}</span>
            </el-form-item>
            <el-form-item label="结束时间">
              <span>{{ props.row.endDate }}</span>
            </el-form-item>
            <el-form-item label="创建时间">
              <span>{{ props.row.createTime }}</span>
            </el-form-item>
            <el-form-item label="更新时间">
              <span>{{ props.row.updateTime }}</span>
            </el-form-item>
            <el-form-item label="备注">
              <span>{{ props.row.remark }}</span>
            </el-form-item>
          </el-form>
        </template>
      </el-table-column>
      <!--      <el-table-column align="center" label="城市" prop="city" sortable/>

      <el-table-column align="center" label="区县" prop="area"/>-->

      <el-table-column align="center" label="小区名称" width="80" prop="community"/>
      <el-table-column align="center"  :show-overflow-tooltip="true"width="160" label="房屋全称" prop="fullName"/>
      <el-table-column align="center" width="60" label="租金" prop="rent"/>
      <el-table-column align="center" width="160" label="交租时间" prop="playTime"/>
      <el-table-column align="center" label="付租周期" prop="cycle" width="90">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.cycle === '1'" size="small" type="danger">押一付一</el-tag>
          <el-tag v-if="scope.row.cycle === '2'" size="small" type="success">押一付二</el-tag>
          <el-tag v-if="scope.row.cycle === '3'" size="small" type="success">押一付三</el-tag>
          <el-tag v-if="scope.row.cycle === '4'" size="small" type="success">半年付</el-tag>
          <el-tag v-if="scope.row.cycle === '5'" size="small" type="success">一把付</el-tag>
        </template>
      </el-table-column>
      <!--      <el-table-column align="center" label="房东性别" prop="sex" width="80">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.sex === '0'" size="small" type="success">男</el-tag>
          <el-tag v-if="scope.row.sex === '1'" size="small" type="warning">女</el-tag>
        </template>
      </el-table-column>-->
      <el-table-column align="center" width="110" label="联系方式" prop="phone"/>
      <el-table-column align="center" label="租约状态" prop="leaseStatus" width="100">
        <template slot-scope="scope">
          <!--<el-tag type="primary" style="margin-right: 20px;"> {{ formatLeaseStatus(scope.row.leaseStatus) }} </el-tag>-->
          <el-tag v-if="scope.row.leaseStatus === 1" size="small" type="danger">租约结束</el-tag>
          <el-tag v-if="scope.row.leaseStatus === 0" size="small" type="success">在租</el-tag>
          <el-tag v-if="scope.row.leaseStatus === 2" size="small" type="success">快到期</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" width="110" label="交租状态" prop="playFlag">
        <template slot-scope="scope">
          <!--<el-tag type="primary" style="margin-right: 20px;"> {{ formatLeaseStatus(scope.row.leaseStatus) }} </el-tag>-->
          <el-tag v-if="scope.row.playFlag === 0" size="small" type="success">已交租</el-tag>
          <el-tag v-if="scope.row.playFlag === 1" size="small" type="danger">未交租</el-tag>
          <el-tag v-if="scope.row.playFlag === 2" size="small" type="danger">即将交租</el-tag>
          <el-tag v-if="scope.row.playFlag === 3" size="small" type="danger">欠租</el-tag>
          <el-tag v-if="scope.row.playFlag === 4" size="small" type="danger">其他</el-tag>
        </template>
      </el-table-column>


      <el-table-column align="center" label="操作" width="280" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button v-if="scope.row.playFlag !== 0" type="success" size="mini"
                     @click="addHouseRentPaysVlog(scope.row)">交租

          </el-button>
          <el-button v-permission="['POST /admin/room/update']" type="primary" size="mini" @click="handleUpdate(scope.row)">编辑</el-button>
          <el-button v-permission="['POST /admin/room/delete']" type="danger" size="mini" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <!-- 添加或修改对话框 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="dataForm" label-width="140px">
        <el-row class="block-col-2">
          <el-col :span="11">
            <el-form-item label="城市" prop="city">
              <el-input v-model="dataForm.city"/>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="区县" prop="area">
              <el-input v-model="dataForm.area"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row class="block-col-2">
          <el-col :span="11">
            <el-form-item label="小区名称" prop="community">
              <el-input v-model="dataForm.community"/>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="楼栋号" prop="building">
              <el-input v-model="dataForm.building"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row class="block-col-2">
          <el-col :span="11">
            <el-form-item label="房间号" prop="houseNumber">
              <el-input v-model="dataForm.houseNumber"/>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="房屋全称" prop="fullName">
              <el-input v-model="dataForm.fullName"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row class="block-col-2">
          <el-col :span="11">
            <el-form-item label="房东姓名" prop="landlord">
              <el-input v-model="dataForm.landlord"/>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="房东性别" prop="sex">
              <el-select v-model="dataForm.sex" filterable placeholder="请选择">
                <el-option
                  v-for="item in sexOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row class="block-col-2">
          <el-col :span="11">
            <el-form-item label="联系方式" prop="phone">
              <el-input v-model="dataForm.phone"/>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="付租账号" prop="accountNumber">
              <el-input v-model="dataForm.accountNumber"/>
            </el-form-item>

          </el-col>
        </el-row>

        <el-row class="block-col-2">
          <el-col :span="11">
            <el-form-item label="付租周期" prop="cycle">
              <el-select v-model="dataForm.cycle" filterable placeholder="请选择">
                <el-option
                  v-for="item in rentCycleOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="租金价格" prop="rent">
              <el-input v-model="dataForm.rent"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row class="block-col-2">
          <el-col :span="11">
            <el-form-item label="电户号" prop="electricNumber">
              <el-input v-model="dataForm.electricNumber"/>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="水户号" prop="waterNumber">
              <el-input v-model="dataForm.waterNumber"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row class="block-col-2">
          <el-col :span="11">
            <el-form-item label="燃气户号" prop="gasNumber">
              <el-input v-model="dataForm.gasNumber"/>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="租约状态" prop="leaseStatus">
              <el-select v-model="dataForm.leaseStatus" filterable placeholder="请选择">
                <el-option
                  v-for="item in leaseStatusOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row class="block-col-2">
          <el-col :span="11">
            <el-form-item label="交租时间" prop="beginDate">
              <el-date-picker
                v-model="dataForm.playTime"
                value-format="yyyy-MM-dd"
                type="date"
                placeholder="选择日期"/>
            </el-form-item>
          </el-col>
          <el-col :span="11">
          <el-form-item label="备注" prop="remark">
            <el-input v-model="dataForm.remark"/>
          </el-form-item>
          </el-col>
        </el-row>
        <el-row class="block-col-2">
          <el-col :span="11">
            <el-form-item label="起租时间" prop="beginDate">
              <el-date-picker
                v-model="dataForm.beginDate"
                value-format="yyyy-MM-dd HH:mm:ss"
                type="datetime"
                placeholder="选择日期"/>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="结束时间" prop="endDate">
              <el-date-picker
                v-model="dataForm.endDate"
                value-format="yyyy-MM-dd HH:mm:ss"
                type="datetime"
                placeholder="选择日期"/>
            </el-form-item>
          </el-col>
        </el-row>


        <!--        <el-form-item label="管理员头像" prop="avatar">
          <el-upload
            :headers="headers"
            :action="uploadPath"
            :show-file-list="false"
            :on-success="uploadAvatar"
            class="avatar-uploader"
            accept=".jpg,.jpeg,.png,.gif">
            <img v-if="dataForm.avatar" :src="dataForm.avatar" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"/>
          </el-upload>
        </el-form-item>
        <el-form-item label="管理员角色" prop="roleIds">
          <el-select v-model="dataForm.roleIds" multiple placeholder="请选择">
            <el-option
              v-for="item in roleOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"/>
          </el-select>
        </el-form-item>-->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="createData">确定</el-button>
        <el-button v-else type="primary" @click="updateData">确定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<style>
  .demo-table-expand {
    font-size: 0;
  }
  .demo-table-expand label {
    width: 90px;
    color: #99a9bf;
  }
  .demo-table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
    width: 50%;
  }
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #20a0ff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}
.avatar {
  width: 145px;
  height: 145px;
  display: block;
}
</style>

<script>
import { listHouse, createHouse, updateHouse, deleteHouse, playFlagUpdate,houseplay } from '@/api/house'
import { addHouseRentPay } from '@/api/rentPay'
import { roleOptions } from '@/api/role'
import { uploadPath } from '@/api/storage'
import { getToken } from '@/utils/auth'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination

export default {
  name: 'Admin',
  components: { Pagination },
  data() {
    return {
      uploadPath,
      list: null,
      total: 0,
      roleOptions: null,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        playFlag: undefined,
        playTime: undefined,
        leaseStatus: undefined,
        community: undefined,
        fullName: undefined,
        landlord: undefined,
        sort: 'add_time',
        order: 'desc'
      },
      rentCycleOptions: [{
        value: '1',
        label: '押一付一'
      }, {
        value: '2',
        label: '押一付二'
      }, {
        value: '3',
        label: '押一付三'
      }, {
        value: '4',
        label: '半年付'
      }, {
        value: '5',
        label: '一把付'
      }],
      sexOptions: [{
        value: '0',
        label: '男'
      }, {
        value: '1',
        label: '女'
      }],
      playStatusOptions: [{
        value: 0,
        label: '已交租'
      }, {
        value: 1,
        label: '未交租'
      }, {
        value: 2,
        label: '即将交租'
      },
        {
          value: 3,
          label: '欠租'
        },
        {
          value: 4,
          label: '其他'
        }],

      leaseStatusOptions: [{
        value: 0,
        label: '在租中'
      }, {
        value: 1,
        label: '租约结束'
      }, {
        value: 2,
        label: '快到期'
      },
        {
        value: 3,
        label: '其他'
      }],

      dataForm: {
        // id: undefined,
        // username: undefined,
        // password: undefined,
        // avatar: undefined,
        // roleIds: []
        id: undefined,
        nowMonthPlayFlag: undefined,
        housePlayFlag: undefined,
        userId: undefined,
        city: '合肥',
        area: undefined,
        community: undefined,
        building: undefined,
        houseNumber: undefined,
        fullName: undefined,
        landlord: undefined,
        sex: undefined,
        phone: undefined,
        accountNumber: undefined,
        cycle: undefined,
        rent: undefined,
        beginDate: undefined,
        endDate: undefined,
        leaseStatus: undefined,
        electricNumber: undefined,
        waterNumber: undefined,
        gasNumber: undefined,
        createTime: undefined,
        updateTime: undefined,
        remark: undefined,
        delFlag: undefined,
        roomRent: 0
      },
      dialogTableVisible: false,
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '创建'
      },
      rules: {
        fullName: [{ required: true, message: '房屋全程不能卫空', trigger: 'blur' }],
        landlord: [{ required: true, message: '房东姓名不能为空', trigger: 'blur' }]
        /*        phone: [{required: true, message: '联系方式不能为空', trigger: 'blur'}],*/
        /*        electricNumber: [{required: true, message: '电费号不能为空', trigger: 'blur'}],
        waterNumber: [{required: true, message: '水费号不能为空', trigger: 'blur'}],*/
        /*        beginDate: [{required: true, message: '入住时间不能为空', trigger: 'blur'}],*/
        /*        endDate: [{required: true, message: '结束时间不能为空', trigger: 'blur'}]*/
      },
      downloadLoading: false
    }
  },
  computed: {
    headers() {
      return {
        'X-Litemall-Admin-Token': getToken()
      }
    }
  },
  created() {
    this.getList()

    roleOptions()
      .then(response => {
        this.roleOptions = response.data.data.list
      })
  },
  methods: {
    formatLeaseStatus(leaseStatusValue) {
      console.log(leaseStatusValue)
      for (let i = 0; i < this.leaseStatusOptions.length; i++) {
        if (leaseStatusValue === this.leaseStatusOptions[i].value) {
          return this.leaseStatusOptions[i].label
        }
      }
      return ''
    },
    addHouseRentPaysVlog(row) {
/*      var values = this.formatRoomRent(row.roomId)*/
      var values = row.rent
      if(row.cycle==='2'){
        values=values*2
      }
      if(row.cycle==='3'){
        values=values*3
      }
      if(row.cycle==='4'){
        values=values*6
      }

      this.$prompt('是否确认已收租,并输入交租金额', '输入交租金额', {
        confirmButtonText: '保存',
        cancelButtonText: '取消',
        dangerouslyUseHTMLString: true,
        showInput:true,
        inputValue: values
      }).then(({ value }) => {
        var params = {"cycle": row.cycle,"playTime": row.playTime, "id": row.id,"rent": value, "userId": this.$store.state.user.name}
        addHouseRentPay(params)
          .then(() => {
            this.$notify.success({
              title: '成功',
              message: '交付金额: ' + value
            })
            this.listQuery.page = 1
            this.getList()
          })
          .catch(response => {
            this.$notify.error({
              title: '失败',
              message: response.data.errmsg
            })
          })
      });
    },
    formatRole(roleId) {
      for (let i = 0; i < this.roleOptions.length; i++) {
        if (roleId === this.roleOptions[i].value) {
          return this.roleOptions[i].label
        }
      }
      return ''
    },
    getList() {
      this.listLoading = true
      listHouse(this.listQuery)
        .then(response => {
          this.list = response.data.data.list
          this.total = response.data.data.total
          this.listLoading = false
        })
        .catch(() => {
          this.list = []
          this.total = 0
          this.listLoading = false
        })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleDelete(row) {
      this.$confirm('是否确认已删除？', '确认信息', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(() => {
        row.delFlag = 1
        updateHouse(row)
          .then(response => {
            this.$notify.success({
              title: '成功',
              message: '删除成功'
            })
            const index = this.list.indexOf(row)
            this.list.splice(index, 1)
          })
          .catch(response => {
            this.$notify.error({
              title: '失败',
              message: response.data.errmsg
            })
          })
      })
    },
    updataRenovate() {
      this.listLoading = true
      houseplay(this.listQuery)
        .then(response => {
          this.list = response.data.data.list
          this.total = response.data.data.total
          this.listLoading = false
        })
        .catch(() => {
          this.list = []
          this.total = 0
          this.listLoading = false
        })
    },
    resetForm() {
      this.dataForm = {
        userId: undefined,
        city: undefined,
        area: undefined,
        community: undefined,
        building: undefined,
        houseNumber: undefined,
        fullName: undefined,
        landlord: undefined,
        sex: undefined,
        phone: undefined,
        accountNumber: undefined,
        cycle: undefined,
        rent: undefined,
        beginDate: undefined,
        endDate: undefined,
        leaseStatus: undefined,
        electricNumber: undefined,
        waterNumber: undefined,
        gasNumber: undefined,
        createTime: undefined,
        updateTime: undefined,
        remark: undefined,
        nowMonthPlayFlag: undefined,
        housePlayFlag: undefined,
        delFlag: undefined
      }
    },
    uploadAvatar: function(response) {
      this.dataForm.avatar = response.data.url
    },
    handleCreate() {
      this.resetForm()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          createHouse(this.dataForm)
            .then(response => {
              this.list.unshift(response.data.data)
              this.dialogFormVisible = false
              this.$notify.success({
                title: '成功',
                message: '添加房屋信息成功'
              })
            })
            .catch(response => {
              this.$notify.error({
                title: '失败',
                message: response.data.errmsg
              })
            })
        }
      })
    },
    handleUpdate(row) {
      this.dataForm = Object.assign({}, row)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          updateHouse(this.dataForm)
            .then(() => {
              for (const v of this.list) {
                if (v.id === this.dataForm.id) {
                  const index = this.list.indexOf(v)
                  this.list.splice(index, 1, this.dataForm)
                  break
                }
              }
              this.dialogFormVisible = false
              this.$notify.success({
                title: '成功',
                message: '更新房屋成功'
              })
            })
            .catch(response => {
              this.$notify.error({
                title: '失败',
                message: response.data.errmsg
              })
            })
        }
      })
    },
    nowHousePlayFlagUpdate() {
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['房间ID', '房间名称', '房间头像']
        const filterVal = ['id', 'username', 'avatar']
        excel.export_json_to_excel2(
          tHeader,
          this.list,
          filterVal,
          '房间信息'
        )
        this.downloadLoading = false
      })
    }
  }
}
</script>
